#include <WebServer.h>
#include <cstring>
#include <unistd.h>
#include <errs.h>
#include <cerrno>
#include <cstdio>
#include <EventLoop.h>
#include <Channel.h>

WebServer::WebServer(uint16_t port, bool openLog, int logLevel, int logSize)
{
    // log initialize
    if (openLog) {
        log = Log::getInstance();
        log->init(logLevel, "./log", ".logg", logSize);
        LOG_DEBUG("Logger start...");
    }
    _loop = new EventLoop();
    _acceptor = new Acceptor(_loop);
    std::function<void(Socket *)> cb = std::bind(&WebServer::handleConnection, this, std::placeholders::_1);
    _acceptor->setConnectionCallback(cb);
}

WebServer::~WebServer()
{
    delete _loop;
    delete _acceptor;
}

void WebServer::start()
{
    // 事件循环
    _loop->loop();
}

/**
 * @brief 处理客户端连接
 *
 */
void WebServer::handleConnection(Socket *sock)
{
    if (sock->getFd() != -1)
    {
        Connection *conn = new Connection(_loop, sock);
        // 设定删除连接回调函数
        std::function<void(Socket *)> cb = std::bind(&WebServer::deleteConnection, this, std::placeholders::_1);
        conn->setDeleteConnectionCallback(cb);
        // 添加至Map
        _map[sock->getFd()] = conn;
    }
}

/**
 * @brief 断开TCP连接
 *
 * @param sock 客户端套接字
 */
void WebServer::deleteConnection(Socket *sock)
{
    if (sock == nullptr) return;    // solve segmentation fault.
    int fd = sock->getFd();
    if (fd != -1)
    {
        auto it = _map.find(fd);
        if (it != _map.end())
        {
            Connection *conn = _map[fd];
            _map.erase(fd);
            delete conn;
        }
    }
}
